package com.liuche.wiki.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuche.wiki.annotation.AuthCheck;
import com.liuche.wiki.common.BaseResponse;
import com.liuche.wiki.common.DeleteRequest;
import com.liuche.wiki.common.ErrorCode;
import com.liuche.wiki.common.ResultUtils;
import com.liuche.wiki.constant.UserConstant;
import com.liuche.wiki.exception.BusinessException;
import com.liuche.wiki.exception.ThrowUtils;
import com.liuche.wiki.model.dto.wiki.WikiArticleAddRequest;
import com.liuche.wiki.model.dto.wiki.WikiArticleEditRequest;
import com.liuche.wiki.model.dto.wiki.WikiArticleQueryRequest;
import com.liuche.wiki.model.dto.wiki.WikiArticleUpdateRequest;
import com.liuche.wiki.model.entity.WikiArticle;
import com.liuche.wiki.model.entity.User;
import com.liuche.wiki.model.vo.WikiArticleVO;
import com.liuche.wiki.service.WikiArticleService;
import com.liuche.wiki.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 知识库文章接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/wikiArticle")
@Slf4j
public class WikiArticleController {

    @Resource
    private WikiArticleService wikiArticleService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建知识库文章
     *
     * @param wikiArticleAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addWikiArticle(@RequestBody WikiArticleAddRequest wikiArticleAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(wikiArticleAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        WikiArticle wikiArticle = new WikiArticle();
        BeanUtils.copyProperties(wikiArticleAddRequest, wikiArticle);
        // 数据校验
        wikiArticleService.validWikiArticle(wikiArticle, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        wikiArticle.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = wikiArticleService.save(wikiArticle);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newWikiArticleId = wikiArticle.getId();
        return ResultUtils.success(newWikiArticleId);
    }

    /**
     * 删除知识库文章
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteWikiArticle(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        WikiArticle oldWikiArticle = wikiArticleService.getById(id);
        ThrowUtils.throwIf(oldWikiArticle == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldWikiArticle.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = wikiArticleService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新知识库文章（仅管理员可用）
     *
     * @param wikiArticleUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateWikiArticle(@RequestBody WikiArticleUpdateRequest wikiArticleUpdateRequest) {
        if (wikiArticleUpdateRequest == null || wikiArticleUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        WikiArticle wikiArticle = new WikiArticle();
        BeanUtils.copyProperties(wikiArticleUpdateRequest, wikiArticle);
        // 数据校验
        wikiArticleService.validWikiArticle(wikiArticle, false);
        // 判断是否存在
        long id = wikiArticleUpdateRequest.getId();
        WikiArticle oldWikiArticle = wikiArticleService.getById(id);
        ThrowUtils.throwIf(oldWikiArticle == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = wikiArticleService.updateById(wikiArticle);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取知识库文章（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<WikiArticleVO> getWikiArticleVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        WikiArticle wikiArticle = wikiArticleService.getById(id);
        ThrowUtils.throwIf(wikiArticle == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(wikiArticleService.getWikiArticleVO(wikiArticle, request));
    }

    /**
     * 分页获取知识库文章列表（仅管理员可用）
     *
     * @param wikiArticleQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<WikiArticle>> listWikiArticleByPage(@RequestBody WikiArticleQueryRequest wikiArticleQueryRequest) {
        long current = wikiArticleQueryRequest.getCurrent();
        long size = wikiArticleQueryRequest.getPageSize();
        // 查询数据库
        Page<WikiArticle> wikiArticlePage = wikiArticleService.page(new Page<>(current, size),
                wikiArticleService.getQueryWrapper(wikiArticleQueryRequest));
        return ResultUtils.success(wikiArticlePage);
    }

    /**
     * 分页获取知识库文章列表（封装类）
     *
     * @param wikiArticleQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<WikiArticleVO>> listWikiArticleVOByPage(@RequestBody WikiArticleQueryRequest wikiArticleQueryRequest,
                                                               HttpServletRequest request) {
        long current = wikiArticleQueryRequest.getCurrent();
        long size = wikiArticleQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<WikiArticle> wikiArticlePage = wikiArticleService.page(new Page<>(current, size),
                wikiArticleService.getQueryWrapper(wikiArticleQueryRequest));
        // 获取封装类
        return ResultUtils.success(wikiArticleService.getWikiArticleVOPage(wikiArticlePage, request));
    }

    /**
     * 分页获取当前登录用户创建的知识库文章列表
     *
     * @param wikiArticleQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<WikiArticleVO>> listMyWikiArticleVOByPage(@RequestBody WikiArticleQueryRequest wikiArticleQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(wikiArticleQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        wikiArticleQueryRequest.setUserId(loginUser.getId());
        long current = wikiArticleQueryRequest.getCurrent();
        long size = wikiArticleQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<WikiArticle> wikiArticlePage = wikiArticleService.page(new Page<>(current, size),
                wikiArticleService.getQueryWrapper(wikiArticleQueryRequest));
        // 获取封装类
        return ResultUtils.success(wikiArticleService.getWikiArticleVOPage(wikiArticlePage, request));
    }

    /**
     * 编辑知识库文章（给用户使用）
     *
     * @param wikiArticleEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editWikiArticle(@RequestBody WikiArticleEditRequest wikiArticleEditRequest, HttpServletRequest request) {
        if (wikiArticleEditRequest == null || wikiArticleEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        WikiArticle wikiArticle = new WikiArticle();
        BeanUtils.copyProperties(wikiArticleEditRequest, wikiArticle);
        // 数据校验
        wikiArticleService.validWikiArticle(wikiArticle, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = wikiArticleEditRequest.getId();
        WikiArticle oldWikiArticle = wikiArticleService.getById(id);
        ThrowUtils.throwIf(oldWikiArticle == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldWikiArticle.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = wikiArticleService.updateById(wikiArticle);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
